package com.example.singing.manager;

import com.example.singing.model.Competition;
import com.example.singing.util.FileUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 比赛管理类
 */
public class CompetitionManager {
    private List<Competition> competitions;
    private static final String COMPETITION_FILE = "competitions.dat";

    public CompetitionManager() {
        this.competitions = new ArrayList<>();
        loadCompetitions();
        // 移除示例数据，不再自动添加
    }

    /**
     * 添加比赛
     */
    public void addCompetition(Competition competition) {
        competitions.add(competition);
        saveCompetitions();
    }

    /**
     * 根据ID获取比赛
     */
    public Competition getCompetitionById(String id) {
        for (Competition competition : competitions) {
            if (competition.getId().equals(id)) {
                return competition;
            }
        }
        return null;
    }

    /**
     * 获取所有比赛
     */
    public List<Competition> getAllCompetitions() {
        return new ArrayList<>(competitions);
    }

    /**
     * 更新比赛
     */
    public void updateCompetition(Competition updatedCompetition) {
        for (int i = 0; i < competitions.size(); i++) {
            if (competitions.get(i).getId().equals(updatedCompetition.getId())) {
                competitions.set(i, updatedCompetition);
                saveCompetitions();
                return;
            }
        }
    }

    /**
     * 删除比赛
     */
    public boolean deleteCompetition(String id) {
        System.out.println("尝试删除比赛ID: " + id);
        System.out.println("删除前比赛总数: " + competitions.size());
        
        boolean removed = competitions.removeIf(c -> {
            boolean shouldRemove = c.getId().equals(id);
            if (shouldRemove) {
                System.out.println("找到要删除的比赛: " + c.getId() + ", 名称: " + c.getName());
            }
            return shouldRemove;
        });
        
        System.out.println("删除操作结果: " + removed);
        System.out.println("删除后比赛总数: " + competitions.size());
        
        if (removed) {
            try {
                saveCompetitions();
                System.out.println("比赛数据已保存到文件");
            } catch (Exception e) {
                System.err.println("删除比赛后保存数据失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
        return removed;
    }
    
    /**
     * 删除比赛（带级联删除队伍和评分）
     */
    public boolean deleteCompetitionWithCascade(String id, com.example.singing.manager.ScoreManager scoreManager, com.example.singing.manager.TeamManager teamManager) {
        System.out.println("尝试级联删除比赛ID: " + id);
        
        // 先删除相关的评分数据
        if (scoreManager != null) {
            List<com.example.singing.model.Score> relatedScores = scoreManager.getScoresByCompetitionId(id);
            System.out.println("找到相关评分数量: " + relatedScores.size());
            
            for (com.example.singing.model.Score score : relatedScores) {
                boolean scoreDeleted = scoreManager.deleteScoreById(score.getId());
                System.out.println("删除评分 " + score.getId() + " 结果: " + scoreDeleted);
            }
        }
        
        // 再删除相关的队伍数据
        if (teamManager != null) {
            List<com.example.singing.model.Team> relatedTeams = teamManager.getAllTeams().stream()
                    .filter(team -> id.equals(team.getCompetitionId()))
                    .collect(java.util.stream.Collectors.toList());
            System.out.println("找到相关队伍数量: " + relatedTeams.size());
            
            for (com.example.singing.model.Team team : relatedTeams) {
                boolean teamDeleted = teamManager.deleteTeam(team.getId());
                System.out.println("删除队伍 " + team.getId() + " 结果: " + teamDeleted);
            }
        }
        
        // 最后删除比赛
        return deleteCompetition(id);
    }

    /**
     * 保存比赛数据
     */
    public void saveCompetitions() {
        FileUtil.saveData(competitions, COMPETITION_FILE);
    }

    /**
     * 加载比赛数据
     */
    @SuppressWarnings("unchecked")
    public void loadCompetitions() {
        Object data = FileUtil.loadData(COMPETITION_FILE);
        if (data != null) {
            competitions = (List<Competition>) data;
        }
    }

    /**
     * 添加示例数据
     */
    private void addSampleData() {
        System.out.println("开始创建示例比赛数据...");
        
        Competition comp1 = new Competition("COMP001", "校园歌手大赛", "2023-05-15", "校级", "标准评分规则");
        competitions.add(comp1);
        System.out.println("创建比赛1: " + comp1.getName() + " (ID: " + comp1.getId() + ")");
        
        Competition comp2 = new Competition("COMP002", "青春歌唱比赛", "2023-06-20", "院级", "加权评分规则");
        competitions.add(comp2);
        System.out.println("创建比赛2: " + comp2.getName() + " (ID: " + comp2.getId() + ")");
        
        Competition comp3 = new Competition("COMP003", "金嗓子歌唱比赛", "2023-07-10", "省级", "标准评分规则");
        competitions.add(comp3);
        System.out.println("创建比赛3: " + comp3.getName() + " (ID: " + comp3.getId() + ")");
        
        System.out.println("示例比赛创建完成，总数: " + competitions.size());
        saveCompetitions();
    }
}